package com.dmcliver.timetracker.service;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.jboss.seam.annotations.AutoCreate;
import org.jboss.seam.annotations.Name;

@AutoCreate
@Name("standardHashService")
public class StandardHashServiceImpl implements StandardHashService {

	private MessageDigest md;

	public StandardHashServiceImpl() throws NoSuchAlgorithmException {
		md = MessageDigest.getInstance("SHA-512");
	}
	
	public String hash(String text){
		
		byte[] bytes = text.getBytes();
		byte[] digest = md.digest(bytes);
		String result = byteArrayToHex(digest);
		return result;
	}

	private String byteArrayToHex(byte[] digest) {
		
		StringBuffer sb = new StringBuffer();
        for (int i = 0; i < digest.length; i++) {
        	
        	String output = Integer.toHexString(digest[i]);
    		output = output.length() == 1 ? "0" + output : output;
    		sb.append(output.substring(output.length() - 2, output.length()));
        }
        return sb.toString();
	}
}
